//
//  CZDetailViewController.swift
//  GZWeibo007
//
//  Created by 韦神 on 15/12/24.
//  Copyright © 2015年 Apple. All rights reserved.
//

import UIKit
import SVProgressHUD

// 统一管理cell的ID
enum CZStatusDetailIdentifier: String {
    case DetailStatusNormalCell = "DetailStatusNormalCell"
    case DetailStatusForwardCell = "DetailStatusForwardCell"
//    case DetailCommentCell = "DetailCommentCell"
//    case DetailLoadingCell = "DetailLoadingCell"
//    case DetailNoDataCell = "DetailNoDataCell"
    
    // 判断返回对应的cellId
//    static func cellId(obj: AnyObject) -> String {
//        if obj is CZStatus {
//            return (obj as! CZStatus).retweeted_status == nil ? DetailStatusNormalCell.rawValue : DetailStatusForwardCell.rawValue
//        } else if obj is CZDetailCommentModel {
//           return (obj as! CZDetailCommentModel).loading ? DetailLoadingCell.rawValue : DetailCommentCell.rawValue
//        }
//        
//        return DetailStatusNormalCell.rawValue
//    }
}

class CZDetailViewController: UITableViewController, CZRetweetStatusDelegate, CZStatusBottomViewDelegate {

    private var status: CZStatus
    
    init(status: CZStatus) {
        self.status = status
        super.init(nibName: nil, bundle: nil)
    }
 
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    /// 评论数据
    var statuses: [CZStatus]? {
        didSet {
            self.tableView.reloadData()
        }
    }
    
    

    ///MARK: - 加载评论数据
    func loadMoreStatus() {
        // 如果没有微博数据, since_id设置为0,加载最新的20条
        // 如果有微博数据,获取最大id的微博
        let since_id = statuses?.first?.id ?? 0
        let max_id = 0
        
        // 1.调用微博模型来加载微博数据(微博模型),
        // 2.准备闭包
        
        CZStatus.mLoadDiscussCell(status.id, since_id: since_id, max_id: max_id, count: 3) { (statuses, error) -> () in
            
//            self.tableView.infiniteScrollingView.stopAnimating()
            
            if error != nil  {
                return
            }
            //没有出错
            let count = statuses?.count ?? 0
            //判断如果是上拉刷新，显示
            if count == 0
            {
                return
            }
            //加载到数据
            self.statuses = statuses!
            
           
            
            // 需要显示上拉加载更多地菊花
            self.tableView.showsInfiniteScrolling = true
        }
        
            
        }

    //MARK: - 再发一次请求 完成上拉加载更多数据
    /// 上拉加载更多数据
    func loadOldStatus() {
        let since_id = 0
        let max_id = statuses?.last?.id ?? 0
        
       CZStatus.mLoadDiscussCell(status.id, since_id: since_id, max_id: max_id, count: 3) { (statuses, error) -> () in
            // 关闭上拉加载更多数据的控件
            self.tableView.infiniteScrollingView.stopAnimating()
            
            if error != nil {
                return
            }
            
            // 没有出错
            let count = statuses?.count ?? 0
        
        
            if count == 0 {
                return
            }
            
            // 加载到了数据
            if max_id > 0 {
                // 最终的数据 = 现有数据 + 获取到的数据
                self.statuses = self.statuses! + statuses!
            }
        }
    }

    
    override func viewDidLoad() {
        super.viewDidLoad()

        
        
        
        title = "微博详情"
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", style: UIBarButtonItemStyle.Plain, target: self, action: "detaiControllerDimiss")
        //注册Cell
        //TODO:注册的CellID与主页的不同

        tableView.registerClass(CZStatusNormalCell.self, forCellReuseIdentifier: CZStatusDetailIdentifier.DetailStatusNormalCell.rawValue )
        
       
        
        tableView.registerClass(CZStatusForwardCell.self, forCellReuseIdentifier: CZStatusDetailIdentifier.DetailStatusForwardCell.rawValue)
        
        
        
        tableView.registerClass(CZDiscussCell.self, forCellReuseIdentifier: "cell")
        //将底部View添加到window中
        
        UIApplication.sharedApplication().delegate?.window!!.addSubview(bottomView)
        // 去掉cell的分割线
        tableView.separatorStyle = UITableViewCellSeparatorStyle.None
        
        // 加载更多数据
        self.loadMoreStatus()
    
    
        
        tableView.addInfiniteScrollingWithActionHandler { () -> Void in
            
            
            // 加载更多数据
            self.loadOldStatus()
        }
        
        // 先不显示上拉加载更多的菊花
        tableView.showsInfiniteScrolling = false

    
    }
    //MARK: - 返回
    func detaiControllerDimiss() {
        UIView.animateWithDuration(0.25, animations: { () -> Void in
            self.bottomView.frame.origin.x = UIScreen.mainScreen().bounds.size.width
            }) { (_) -> Void in
                self.bottomView.removeFromSuperview()
        }
        
        navigationController?.popViewControllerAnimated(true)
    }



    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {

        
        return 2
    }

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows

        
        
        if section == 0
        {
            return 1
        }else
        {
            return statuses?.count ?? 0
        }
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        //第一组
        if 0 == indexPath.section {

                let cellID = status.retweeted_status == nil ? CZStatusDetailIdentifier.DetailStatusNormalCell.rawValue : CZStatusDetailIdentifier.DetailStatusForwardCell.rawValue
            
        let cell = tableView.dequeueReusableCellWithIdentifier(cellID) as! CZStatusCell
        
        // 设置cell的微博模型
        cell.status = status
        cell.retweetStatusDelegate = self
        return cell
        }
        //第二组

            // 取出对应的模型
            let status1 = statuses![indexPath.row]
        
            let cell = tableView.dequeueReusableCellWithIdentifier("cell") as! CZDiscussCell
            cell.status = status1

            return cell
 
    }
    
    
    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        
        if 0 == indexPath.section {
                    // 根据 微博模型 获取cell的 重用标示
        let cellId = status.retweeted_status == nil ? CZStatusDetailIdentifier.DetailStatusNormalCell.rawValue : CZStatusDetailIdentifier.DetailStatusForwardCell.rawValue
        
        // 根据 重用标示 获取对应的cell
        let cell = tableView.dequeueReusableCellWithIdentifier(cellId) as! CZStatusCell
        
        // 根据模型来计算 微博cell的高度
            if nil == status.rowHeight {
                let rowHeight = cell.rowHeight(status)
                
                
                
                return rowHeight
                

            }
            return status.rowHeight!
        }
        
        return 80
    }
    
    override func tableView(tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        if section == 0{
            return headView
        }
        return nil

    }
    
    override func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        if section == 0 {
            return 30
        }
        
        return 0
    }
    

    
    
    
    
    
    //MARK: - 被转发微博代理实现
    func retweetStatusClick(status: CZStatus) {
        //        if nil == status.rowHeight {
        //            let cellID = status.cellID()
        //            let cell = tableView.dequeueReusableCellWithIdentifier(cellID) as! CZStatusCell
        //
        //            // 4.使用cell计算行高,每次都计算行高需要消耗性能,将行高进行缓存,行高是根据模型算出来的.行高缓存在模型中最合适
        //            let rowHeight = cell.rowHeight(status)
        //
        //            // 5.保存计算好的行高
        //            status.rowHeight = rowHeight
        //        }
        //        print("点击代理方法")
        
        let detailVc = CZDetailViewController(status: status)
        detailVc.hidesBottomBarWhenPushed = true
        
        navigationController?.pushViewController(detailVc, animated: true)
    }


//    头部view
        lazy var headView:UILabel = {
            let label = UILabel()
            label.textAlignment = NSTextAlignment.Left
            label.font = UIFont.systemFontOfSize(14)
            label.textColor = UIColor.darkGrayColor()
            label.text = "     评论"
            
            label.backgroundColor = UIColor(white: 0.8, alpha: 1)
            label.frame = CGRect(x: 0, y: 0, width: UIScreen.mainScreen().bounds.width, height: 44)
            return label
            }()
    
    //MARK: - bottomView代理方法实现
    func forwardButtonClick() {
        
        let retweetVc  = CZModalViewController(comtent: modalType.modalTypeTransmitStatu)
//        retweetVc.delegate = self
        //隐藏bottomView
//        bottomView.hidden = true
        
        retweetVc.status = status
        let nav = UINavigationController(rootViewController: retweetVc)
        navigationController?.presentViewController(nav, animated: true, completion: { () -> Void in
            
        })
    }
    
    func commentButtonClick() {
        let commentVc  = CZModalViewController(comtent: modalType.modalTypeCommentStatu)
        //        retweetVc.delegate = self
        //隐藏bottomView
        //        bottomView.hidden = true
        commentVc.status = status
        let nav = UINavigationController(rootViewController: commentVc)
        navigationController?.presentViewController(nav, animated: true, completion: { () -> Void in
        })
    }
    
    func lickButtonClick() {
        SVProgressHUD.showInfoWithStatus("接口暂未开放")
    }
    
    deinit {
        print("详情控制器销毁")
//        bottomView.removeFromSuperview()
    }
    
    

    
    //MARK: - 懒加载控件
    
    lazy var bottomView: CZStatusBottomView = {
        let frame = CGRectMake(0, UIScreen.mainScreen().bounds.height-44, UIScreen.mainScreen().bounds.width, 44)
        let bottomV = CZStatusBottomView(frame: frame)
        bottomV.delegate = self
        return bottomV
    }()
    
//    MARK: - bottomView相关的功能modal控制器代理实现
    func modalViewSendStatusClick(){
        print("转发或者评论")
        bottomView.hidden = false
    }
    func modalViewCancelStatusClick() {
        bottomView.hidden = false
    }

}
